import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class TempView extends StatefulWidget {
  const TempView({super.key});

  @override
  State<StatefulWidget> createState() => _TempViewState();
}

class _TempViewState extends State<TempView> {
  String response = "期待您的提问";
  final userInputController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("物理题问答"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
              ),
              controller: userInputController,
              minLines: 5,
              maxLines: 10,
            ),
            const Text("输出结果"),
            Text(
              response,
              style: const TextStyle(
                overflow: TextOverflow.fade,
              ),
            ),
          ],
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        child: ElevatedButton(
          onPressed: () async {
            final response = await http.post(
              Uri.parse('http://10.199.194.160:10256/v1/ask'),
              headers: <String, String>{
                'Content-Type': 'application/json; charset=UTF-8',
                'Accept': 'application/text',
              },
              body: jsonEncode(
                <String, dynamic>{
                  "question": userInputController.text,
                },
              ),
            );
            this.response = utf8.decode(response.bodyBytes);
            this.response =
                this.response.substring(1, this.response.length - 1);
            this.response = this.response.replaceAll("\\n", "\n");
            setState(() {});
          },
          child: const Text(
            "点击提问",
          ),
        ),
      ),
    );
  }
}
